import {ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'

export function useRoleOperations(tableData, searchResults, hasSearched, formatDateTime) {
    const loading = ref(false)

    // 统一的保存逻辑
    const saveRole = async (form, isEdit = false, originalId = null) => {
        try {
            // 参数验证
            if (!form || typeof form !== 'object') {
                ElMessage.error('表单数据无效')
                return false
            }

            // 表单验证
            if (!form.roleName) {
                ElMessage.error('请选择角色')
                return false
            }

            if (!Array.isArray(form.permissions) || form.permissions.length === 0) {
                ElMessage.error('请至少选择一个权限')
                return false
            }

            const currentTime = formatDateTime ? formatDateTime(new Date()) : new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }).replace(/\//g, '-').replace(',', '');

            if (isEdit) {
                // 更新角色
                if (!tableData.value || !Array.isArray(tableData.value)) {
                    ElMessage.error('表格数据无效')
                    return false
                }
                
                const index = tableData.value.findIndex(item => item && item.id === originalId)
                if (index !== -1) {
                    tableData.value[index] = {
                        ...tableData.value[index],
                        roleName: form.roleName,
                        description: form.description || '',
                        permissions: [...form.permissions],
                        status: form.status ? 1 : 0,
                        updateTime: currentTime
                    }

                    // 更新搜索结果
                    if (hasSearched.value && searchResults.value && Array.isArray(searchResults.value)) {
                        const searchIndex = searchResults.value.findIndex(item => item && item.id === originalId)
                        if (searchIndex !== -1) {
                            searchResults.value[searchIndex] = {...tableData.value[index]}
                        }
                    }
                }
                ElMessage.success('角色更新成功')
            } else {
                // 添加角色（为现有用户分配角色）
                if (!tableData.value || !Array.isArray(tableData.value)) {
                    ElMessage.error('表格数据无效')
                    return false
                }
                
                // 检查是否选择了用户
                if (!form.userId) {
                    ElMessage.error('请选择用户')
                    return false
                }
                
                // 查找用户是否已存在角色分配
                const existingIndex = tableData.value.findIndex(item => item && item.userId === form.userId)
                
                const newRole = {
                    id: existingIndex !== -1 ? tableData.value[existingIndex].id : (tableData.value.length > 0 
                        ? Math.max(...tableData.value.map(item => item && typeof item.id === 'number' ? item.id : 0)) + 1
                        : 1),
                    userId: form.userId,
                    username: form.username || 'unknown_user',
                    roleName: form.roleName,
                    description: form.description || '',
                    permissions: Array.isArray(form.permissions) ? [...form.permissions] : [],
                    status: form.status ? 1 : 0,
                    createTime: existingIndex !== -1 ? tableData.value[existingIndex].createTime : currentTime,
                    updateTime: currentTime
                }

                if (existingIndex !== -1) {
                    // 更新现有用户的权限
                    tableData.value[existingIndex] = {...newRole}
                } else {
                    // 添加新用户角色分配
                    tableData.value.push(newRole)
                }

                // 更新搜索结果
                if (hasSearched.value && searchResults.value && Array.isArray(searchResults.value)) {
                    const searchExistingIndex = searchResults.value.findIndex(item => item && item.userId === form.userId)
                    if (searchExistingIndex !== -1) {
                        searchResults.value[searchExistingIndex] = {...newRole}
                    } else {
                        searchResults.value.push({...newRole})
                    }
                }

                ElMessage.success('角色分配成功')
            }

            return true
        } catch (error) {
            console.error('保存失败:', error)
            ElMessage.error('保存失败: ' + (error.message || '未知错误'))
            return false
        }
    }

    return {
        loading,
        saveRole
    }
}